import re

from rest_framework import serializers

from goods.models import SKU
from .import constants
from .models import User, Address
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_verify_email


class CreateUserSerializers(serializers.ModelSerializer):
    """创建用户序列化器"""
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    # allow = serializers.BooleanField(write_only=True, label='确认同意协议')
    allow = serializers.CharField(write_only=True, label='确认同意协议')
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ['id', 'username', 'password' 'mobile', 'sms_code', 'password2', 'allow', 'token']

        extra_kwargs = {
            'username': {
                'write_only': True,
                'max_length': 20,
                'min_length': 5,
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
            },
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'1[3-9]\d{9}$', value):
            raise  serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """检查用户是否同意用户协议"""
        # if value is not True:
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        raise value

    def validate(self, attrs):
        """检查两次密码是否一致"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 连接redis，取出真实短信验证码，并验证用户填写的验证码
        conn = get_redis_connection('verify_codes')
        real_sms_code = conn.get('sms_%s' % attrs['mobile'])

        if not real_sms_code.decode():
            raise serializers.ValidationError('短信验证码失效')

        if real_sms_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码错误')

        # attrs 就是请求体request的数据data
        return attrs

    def create(self, validated_data):
        """创建用户，即注册"""

        # 移除数据库模型类中不存在的属性,validated_data上面已经验证过的用户数据
        del validated_data['sms_code']
        del validated_data['password2']
        del validated_data['allow']

        # 继承ModelSerializer的create()
        user = super().create(validated_data=validated_data)

        # 调用Django认证系统加密密码，否则是明文存储
        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token,签发JWT的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 添加属性
        user.token = token

        return user


class UserDetailSerializers(serializers.ModelSerializer):
    """用户信息序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailSerializer(serializers.ModelSerializer):
    """邮箱序列化器"""
    class Meta:
        model = User
        fields = ['email', 'id']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):

        instance.email = validated_data['email']
        instance.save()

        # 生成验证链接，发送激活邮件
        verify_url = instance.generate_verify_url()
        send_verify_email.delay(instance.email, verify_url)
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class BrowserSerializers(serializers.Serializer):
    """保存历史浏览记录的序列化器"""
    sku_id = serializers.IntegerField(min_value=1, label='商品的id')

    def validate_sku_id(self, value):
        '''
        校验商品的id
        :param value:
        :return:
        '''
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在！！')

        return value

    def create(self, validated_data):

        # user_id 的获取
        user_id = self.context['request'].user.id
        # sku_id 获取
        sku_id = validated_data['sku_id']

        # 写入redis
        conn = get_redis_connection('history')
        pl = conn.pipeline()

        # 移除已经存在的本商品浏览记录
        pl.lrem("history_%s" % user_id, 0, sku_id)

        # 写入redis
        pl.lpush('history_%s'%user_id, sku_id)
        # 只保存最多5条记录, 按照索引的获取
        pl.ltrim("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)
        pl.execute()

        return validated_data

